package add

import (
	"encoding/base64"
	"fmt"
	"gitee.com/hubdev/api/git/ops"
	v1 "gitee.com/hubdev/api/git/v1"
	"net/http"
	"strings"
)

func init() {
	ops.Register(ops.AddFile, func(url, token string, res *v1.Resource) (*http.Request, error) {
		content := base64.StdEncoding.EncodeToString([]byte(res.Content))
		rd := strings.NewReader(fmt.Sprintf(`{"content":"%s"}`, content))
		api := fmt.Sprintf("%s/contents/%ss/%s/%s.yaml", url, strings.ToLower(res.Kind),res.Metadata.Namespace, res.Metadata.Name)
		req, err := http.NewRequest(http.MethodPost, api, rd)
		if err != nil {
			return nil, err
		}
		if token != ""{
			req.Header.Add("Authorization", fmt.Sprintf("token %s", token))
		}
		req.Header.Add("Content-Type", "application/json")
		return req, err
	})
}
